﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;

namespace SCS.Web.UI.WebControls.Dialogs
{
    public class JsonHelper
    {
        public static string Serialize<T>(T instance)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(instance.GetType());
            MemoryStream stream = new MemoryStream();
            serializer.WriteObject(stream, instance);
            string retVal = Encoding.Default.GetString(stream.ToArray());
            stream.Dispose();
     
            return retVal;
        }

        public static T Deserialize<T>(string json)
        {
            T instance = Activator.CreateInstance<T>();
            MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(json));
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(instance.GetType());
            instance = (T)serializer.ReadObject(stream);
            stream.Close();
            stream.Dispose();
            
            return instance;
        }
    }
}
